//
//  TitleTableViewController.m
//  百度地图
//
//  Created by ljm on 2017/7/10.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "TitleTableViewController.h"

@interface TitleTableViewController ()<UITextFieldDelegate,BMKPoiSearchDelegate,UITableViewDelegate,UITableViewDataSource>

{
    UITextField *_searchF;
    BMKPoiSearch *_searchPOI;
    
    /** 筛选条件字段 **/
    NSString *_searchKeyword;
    
    /** 周边信息数组 **/
    NSMutableArray *_nearDataArr;
    
    UITableView *_searchTableview;
}

@end

@implementation TitleTableViewController

- (void)viewWillAppear      :   (BOOL)animated
{
    [super viewWillAppear   :  animated];
    
    Navigationbar_color     =   RGB(231, 66, 67);
}

- (void)viewWillDisappear   :   (BOOL)animated
{
    [super viewWillDisappear:   animated];
    
    Navigationbar_color     =   [UIColor clearColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor   =   [UIColor whiteColor];
    self.title                  =   @"🔍";
    
    _nearDataArr                =   [NSMutableArray arrayWithCapacity:1];
    
    if (_searchDict.allKeys.count > 0) {
        _searchKeyword          =   [NSString stringWithFormat:@"%@",[_searchDict objectForKey:@"name"]];
    }else
    {
        _searchKeyword          =   @"东航投资大厦";
    }
    
    [self setupUI];
    [self loadTableview];
    [self BMKP0Isearch];
    
}


#pragma mark -- setupUI
- (void) setupUI
{
    UIView *bottomView          =   [[UIView alloc] initWithFrame:CGRectMake(0,
                                                                             64,
                                                                             screenWidth,
                                                                             50)];
    bottomView.backgroundColor  =   [UIColor darkGrayColor];
    [self.view addSubview:bottomView];
    
    _searchF    =   [[UITextField alloc] initWithFrame:CGRectMake(5, 5, screenWidth - 5 * 2, 40)];
    _searchF    .   backgroundColor     =   [UIColor whiteColor];
    _searchF    .   delegate            =   self;
    _searchF    .   layer.cornerRadius  =   5;
    _searchF    .   layer.masksToBounds =   YES;
    
    _searchF    .   textAlignment       =   NSTextAlignmentCenter;
    
    /** 设置水印文字居中 **/
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment            =   NSTextAlignmentCenter;
    
    NSAttributedString *attr            =   [[NSAttributedString alloc] initWithString:@"查找校区、学校、大厦等" attributes:@{NSParagraphStyleAttributeName:paragraphStyle}];
    _searchF    .   attributedPlaceholder = attr;
    
    [_searchF addTarget:self action:@selector(BMKP0Isearch) forControlEvents:UIControlEventTouchDown];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChange:) name:UITextFieldTextDidChangeNotification object:_searchF];
    
    [bottomView addSubview:_searchF];
}

#pragma mark -- 搜索框文字改变
- (void)textFieldEditChange:(NSNotification *)notification
{
 
    UITextField *textField      =   (UITextField *)notification.object;
    
    UITextRange *selectedRange  =   [textField markedTextRange];
    //获取高亮部分
    UITextPosition *position    =   [textField positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position) {
        if (![textField.text isEqualToString:@""]) {
            _searchKeyword      =   textField.text;
            [self BMKP0Isearch];
        }
    }
    
}


#pragma mark -- 百度P0I搜索
- (void) BMKP0Isearch
{
    /** 初始化检索对象 **/
    _searchPOI                          =   [[BMKPoiSearch alloc] init];
    _searchPOI.delegate                 =   self;
    
    BMKCitySearchOption *searchOption   =   [[BMKCitySearchOption alloc] init];
    searchOption.pageCapacity           =   50;
    if (_searchDict.allKeys.count > 0) {
        searchOption.city               =   [_searchDict objectForKey:@"city"];
    }else
    {
        /** 默认城市 **/
        searchOption.city               =   @"昆明";
    }
    searchOption.keyword                =   _searchKeyword;
    
    /** 检索 **/
    BOOL flag = [_searchPOI poiSearchInCity:searchOption];
    if (flag) {
        NSLog(@"========================================\n周边检索成功=================================");
    }else
    {
        NSLog(@"---------------------------------------\n周边检索失败，正在重新检索--------------------------------");
        NSInteger index = 0;
        index ++;
        if (index < 5) {
            [self BMKP0Isearch];
        }
    }
    
}

#pragma mark -- 处理周边检索的回调数据
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode
{
    [_nearDataArr removeAllObjects];
    
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        for (BMKPoiInfo * info in poiResult.poiInfoList) {
            NSDictionary *dic = @{@"address":info.address,
                                  @"name":info.name,
                                  @"locationX":[NSString stringWithFormat:@"%f",info.pt.latitude],
                                  @"locationY":[NSString stringWithFormat:@"%f",info.pt.longitude],@"city":info.city};
            [_nearDataArr addObject:dic];
        }
    }else if (errorCode == BMK_SEARCH_AMBIGUOUS_KEYWORD)
    {
        NSLog(@"索引结果有歧义");
    }else
    {
        NSLog(@"抱歉，未找到结果");
    }
    
    [_searchTableview reloadData];
    if (_nearDataArr.count > 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [_searchTableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

#pragma mark -- 加载tableview
- (void) loadTableview
{
    _searchTableview = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                     64 + _searchF.frame.size.height + 5 * 2,
                                                                     screenWidth,
                                                                     screenHeight - 64 - _searchF.frame.size.height - 10
                                                                     )
                                                    style:UITableViewStylePlain];
    _searchTableview.delegate   = self;
    _searchTableview.dataSource = self;
    [self.view addSubview:_searchTableview];
}

#pragma mark -- uitableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_searchDict.allKeys.count > 0) {
        _searchTableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else
    {
        _searchTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _nearDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
    if (indexPath.row == 0 && _searchDict.allKeys.count > 0) {
        
        static NSString *cellIdentifier = @"cellinden";
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        
        UIImageView *_imageView     =   [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_baidu_marker"]];
        _imageView.frame            =   CGRectMake(20, 15, 20, 30);
        [cell addSubview            :   _imageView];
        
        UILabel *_label             =   [[UILabel alloc] initWithFrame:CGRectMake(
                                                                    _imageView.frame.origin.x + _imageView.frame.size.width + 10,
                                                                    _imageView.frame.origin.y,
                                                                    screenWidth - _imageView.frame.size.width - 10 - _imageView.frame.origin.x,
                                                                    30)];
        _label.text                 =   [NSString stringWithFormat:@"%@(%@)",[_nearDataArr[indexPath.row] objectForKey:@"address"],[_nearDataArr[indexPath.row]objectForKey:@"name"]];
        [cell addSubview:_label];
    }else
    {
        cell.textLabel.text         =   [_nearDataArr[indexPath.row ] objectForKey:@"name"];
        
        cell.detailTextLabel.text   =   [_nearDataArr[indexPath.row ] objectForKey:@"address"];
    }
    
    cell.detailTextLabel.textColor  =   [UIColor lightGrayColor];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = _nearDataArr[indexPath.row];
    [self.navigationController popViewControllerAnimated:YES];
    if (self.titleSearch) {
        self.titleSearch(dic);
    }
//    self.titleSearch(dic);
    
}

#pragma mark -- 将要拖拽tableview时隐藏键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_searchF resignFirstResponder];
}

#pragma mark -- textfield delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (![textField.text isEqualToString:@""]) {
        _searchKeyword = textField.text;
        [self BMKP0Isearch];
    }
    
    [_searchF resignFirstResponder];
    return YES;
}

@end
